/*
 * @Author: guoju
 * @Date: 2021-12-22 09:24:50
 * @LastEditTime: 2022-01-10 14:04:26
 * @LastEditors: guoju
 * @Description: 矩阵
 */

import { useEffect, useState } from 'react';
import { View, Text } from '@tarojs/components';
import styles from './index.module.less';

const MatrixSelect = (props: any) => {
  const {
    subtitles = [],
    extend = [],
    isMutual = 0,
    answer = [],
    setAnswer,
  } = props;

  const [checkedList, setCheckedList] = useState<any>([]);

  useEffect(() => {
    const list = answer.length === 0 ? new Array(subtitles.length) : answer;
    setCheckedList(list);
  }, [answer]);

  const onChangeValue = (item: any, i: number, j: number) => {
    const { answerId } = item;
    let list = JSON.parse(JSON.stringify(checkedList));

    // 点击已选中的则取消
    if (checkedList[i] === answerId) {
      list[i] = null;
    } else {
      // 如果答案互斥, 则不可选择
      if (isMutual === 1 && list.includes(answerId)) {
        return;
      }
      list[i] = answerId;
    }

    setCheckedList(list);
    setAnswer({
      answer: list,
    });
  };

  return (
    <View className={styles.matrixSelectContainer}>
      {subtitles.map((title: any, i: number) => {
        return (
          <View key={String(i)} className={styles.matrixRow}>
            <View className={styles.matrixTitle}>
              {title}
            </View>

            <View className={styles.matrixOption}>
            {extend.map((item: any, j: number) => {
              const isSelect = checkedList[i] === item.answerId;
              const mutual = isMutual === 1 && checkedList.includes(item.answerId);
              return (
                <Text
                  key={`${item.answerId}${j}`}
                  className={`${styles.radioItem} ${
                    isSelect ? styles.active : mutual ? styles.isMutual : ''
                  }`}
                  onClick={() => onChangeValue(item, i, j)}
                >{item.content}</Text>
              )}
            )}
            </View>
          </View>
        );
      })}
    </View>
  );
};

export default MatrixSelect;
